package cn.darkhorse.device.iot.parser;

import cn.darkhorse.device.pojo.IotPointTable;
import cn.darkhorse.device.pojo.MqttData;
import cn.darkhorse.device.service.IotPointTableService;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 星原网关，数据解析器
 */
@Component("sparksIotParser")
public class SparksIotParser extends BaseParser {


    @Override
    Map<String, Object> doParse(MqttData data, String gatewayDeviceId) {
        String json = data.getData();
        JSONObject jsonObject = JSONObject.parse(json);

        // Step.1 获取设备点表
        Set<String> pointIds = getPointIds(gatewayDeviceId);

        // Step.2 解析
        Map<String, Object> pointValueMap = new HashMap<>();
        pointIds.forEach(pointId-> {
            Object o = jsonObject.getJSONObject("params").get(pointId);
            if (o == null) {
                return;
            }
            pointValueMap.put(pointId, o);
        });

//        addToCache(gatewayDeviceId, pointValueMap);
        return pointValueMap;
    }

    @Override
    Map<String, Object> doParse(MqttData data, String gatewayDeviceId, Set<String> pointIds) {
        String json = data.getData();
        JSONObject jsonObject = JSONObject.parse(json);

        // Step.1 获取设备点表
//        Set<String> pointIds = getPointIds(gatewayDeviceId);

        // Step.2 解析
        Map<String, Object> pointValueMap = new HashMap<>();
        pointIds.forEach(pointId-> {
            System.out.println("参数解析");
            System.out.println(pointId);
            Object o = jsonObject.getJSONObject("params").get(pointId);
            System.out.println(o);
            if (o == null) {
                return;
            }
            pointValueMap.put(pointId, o);
        });

//        addToCache(gatewayDeviceId, pointValueMap);
        return pointValueMap;
    }


    @Override
    public LocalDateTime getCreatedAd(MqttData data) {
        String json = data.getData();
        JSONObject jsonObject = JSONObject.parse(json);
        Object o = jsonObject.get("time");
        if (o == null){
            return LocalDateTime.now();
        }
        Long timestamp = Long.parseLong(jsonObject.get("time").toString());
        Instant instant = Instant.ofEpochMilli(timestamp);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

}
